package com.maimao.auth.config.auth;

import com.maimao.auth.model.SysAuthUser;
import com.maimao.auth.service.BaseUserDetailsService;
import com.maimao.core.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 设置jwt信息
 */
@Component("customUserAuthenticationConverter")
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
    @Autowired
    BaseUserDetailsService baseUserDetailsService;

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        LinkedHashMap response = new LinkedHashMap();
        String name = authentication.getName();
        response.put("user_name", name);

        Object principal = authentication.getPrincipal();
        SysAuthUser sysUser = null;
        if (principal instanceof SysAuthUser) {
            sysUser = (SysAuthUser) principal;
        } else {
            //refresh_token默认不去调用userdetailService获取用户信息，这里我们手动去调用，得到 UserJwt
            UserDetails userDetails = baseUserDetailsService.loadUserByUsername(name);
            sysUser = (SysAuthUser) userDetails;
        }
        response.put(Constants.USERNAME, sysUser.getUsername());
        response.put(Constants.ID, sysUser.getId());
        response.put(Constants.AVATAR, sysUser.getAvatar());
        response.put(Constants.TYPE, sysUser.getType());
        response.put(Constants.SHOP_ID, sysUser.getShopId());
        response.put(Constants.REAL_NAME, sysUser.getRealName());
        response.put("role", sysUser.getRole());
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(Constants.AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }


}
